package com.hexagram2021.sweeper_maid.save;

import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.level.saveddata.SavedData;
import com.hexagram2021.sweeper_maid.config.SMCommonConfig;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;

public class SMSavedData extends SavedData {
	@Nullable
	private static SMSavedData INSTANCE;
	public static final String SAVED_DATA_NAME = "SweeperMaid-SavedData";
	private static final String TAG_ITEMS_PREFIX = "Items_"; // 每个垃圾桶的NBT标签前缀（如Items_0、Items_1）

	// 改为列表存储多个垃圾桶
	public final List<SimpleContainer> dustbins;

	// 1. 无参构造：根据配置初始化垃圾桶列表
	public SMSavedData() {
		super();
		int binCount = SMCommonConfig.DUSTBIN_COUNT.get(); // 从配置读垃圾桶数量
		int binSize = SMCommonConfig.DUSTBIN_SIZE.get();   // 从配置读单个垃圾桶大小
		this.dustbins = new ArrayList<>(binCount);

		// 初始化每个垃圾桶（容器修改时标记存档为脏）
		for (int i = 0; i < binCount; i++) {
			this.dustbins.add(new SimpleContainer(binSize) {
				@Override
				public void setChanged() {
					super.setChanged();
					if (INSTANCE != null) {
						INSTANCE.setDirty(); // 触发存档保存
					}
				}
			});
		}
	}

	// 2. NBT构造：从存档加载多个垃圾桶的物品
	public SMSavedData(CompoundTag nbt) {
		this(); // 先初始化列表（按当前配置数量）
		int binCount = this.dustbins.size();

		// 循环加载每个垃圾桶的物品（Items_0 ~ Items_{count-1}）
		for (int i = 0; i < binCount; i++) {
			String tagName = TAG_ITEMS_PREFIX + i;
			SimpleContainer bin = this.dustbins.get(i);
			if (nbt.contains(tagName, Tag.TAG_LIST)) {
				synchronized (bin) {
					bin.fromTag(nbt.getList(tagName, Tag.TAG_COMPOUND));
				}
			}
		}
	}

	// 3. 保存NBT：将多个垃圾桶物品写入存档
	@Override
	public CompoundTag save(CompoundTag nbt) {
		int binCount = this.dustbins.size();
		for (int i = 0; i < binCount; i++) {
			String tagName = TAG_ITEMS_PREFIX + i;
			SimpleContainer bin = this.dustbins.get(i);
			synchronized (bin) {
				nbt.put(tagName, bin.createTag());
			}
		}
		return nbt;
	}

	// 4. 工具方法：获取指定索引的垃圾桶（防越界）
	public static SimpleContainer getDustbin(int index) {
		if (INSTANCE == null) {
			throw new IllegalStateException("SMSavedData is not initialized! This should only be called after the server has started.");
		}
		List<SimpleContainer> bins = INSTANCE.dustbins;
		if (index < 0 || index >= bins.size()) {
			throw new IndexOutOfBoundsException("Dustbin index " + index + " invalid! Range: 0~" + (bins.size() - 1));
		}
		return bins.get(index);
	}

	// 5. 工具方法：获取垃圾桶总数
	public static int getDustbinCount() {
		if (INSTANCE == null) {
			// 服务器未启动完成时，返回配置默认值（避免空指针）
			return SMCommonConfig.DUSTBIN_COUNT.get();
		}
		return INSTANCE.dustbins.size();
	}

	// 6. 保留INSTANCE设置方法
	public static void setInstance(SMSavedData in) {
		INSTANCE = in;
	}

	// 新增：公共 getter 方法，对外提供多垃圾桶列表的访问
	public static List<SimpleContainer> getDustbins() {
		if (INSTANCE == null) {
			throw new IllegalStateException("SMSavedData is not initialized! This should only be called after the server has started.");
		}
		return INSTANCE.dustbins;
	}

}